<!DOCTYPE html>
<html lang="cn">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #dropbox {
            text-align: center;
            line-height: 300px;
            font-size: 30px;
            width: 300px;
            height: 300px;
            background-color: rgba(0, 0, 0, 0.3)
        }
        ul li{
            float: left;
        }
        img{
            width: 100px;
            height: 100px;
        }
    </style>
</head>

<body>
    <div class="out-main-top">
        <div id='dropbox' class='drag-box'>
            将文件拖拽到此处
        </div>
        <button type="button" style="width: 100px; height:30px">上传</button>
    </div>
    <ul id='canvasImg' class='canvas-img'></ul>
</body>

</html>
<script>
    let canvasImg = document.querySelector('#canvasImg');
    // 目标对象
    let dropbox = document.querySelector('#dropbox');
    let allBaseImg = [];
    let AllowImgFileSize = 1024 * 400;

    dropbox.addEventListener('dragover',function(e){
        e.preventDefault()
    })
    dropbox.addEventListener('drop',function(e){
        e.preventDefault();
        let dtfiles=e.dataTransfer.files;
        // console.log( dtfiles[1]);

        transferTobase64(dtfiles)
    })
    function transferTobase64(files){
        for(let i=0;i<files.length;i++){
            let file=files[i];
            // console.log(file);
            let reader=new FileReader();
            // console.log(reader)
            reader.readAsDataURL(file);//异步
            reader.onload = function(e){
                console.log(e)
                let base64Img=e.target.result;
                if(allBaseImg.indexOf(base64Img)!==-1){
                    return;
                }
                if(base64Img.length>AllowImgFileSize){
                    alert('图片上传失败，需要小于400kb');
                    return;
                }
                let str=`<li><img src="${base64Img}"></li>`
                canvasImg.innerHTML+=str;
                allBaseImg.push(base64Img);

            }
        }
    }
</script>